package com.heima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.heima.constant.MessageConstant;
import com.heima.constant.RedisMessageConstant;
import com.heima.entity.Result;
import com.heima.pojo.Order;
import com.heima.service.OrderService;
import com.heima.utils.SMSUtils;
import com.heima.vo.OrderInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.xml.ws.handler.MessageContext;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;


    @RequestMapping("/submit")
    public Result submit(@RequestBody OrderInfo orderInfo){
        if (orderInfo!=null){
            //1比较验证码
            String telephone = orderInfo.getTelephone();
            String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
            String validateCode = orderInfo.getValidateCode();
            if (validateCodeInRedis != null && validateCode!=null && validateCode.equals(validateCodeInRedis)){
                //2验证码校验成功执行业务
                orderInfo.setOrderType(Order.ORDERTYPE_WEIXIN);
                Result result = null;
                try {
                    result = orderService.order(orderInfo);
                } catch (Exception e) {
                    e.printStackTrace();
                    return result;
                }
                //3业务处理成功后发送通知
                if (result.isFlag()){
                    try {
                        SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,orderInfo.getOrderDate().toString());
                    } catch (ClientException e) {
                        e.printStackTrace();
                    }
                }
                return result;
            }else {
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
        }
        return new Result(false,MessageConstant.ORDERSETTING_FAIL);
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map map = orderService.findById(id);
            return new Result(false,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.QUERY_ORDER_FAIL);
        }

    }
}
